package icedot.library.common.utils;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import icedot.library.common.base.BaseActivity;
import icedot.library.common.base.Logger;

/**
 * 处理字符串工具类
 *
 * @author
 */
public class StringUtils
{
    /**
     * 判断是否为空
     *
     * @param text
     * @return
     */
    public static boolean isNullOrEmpty(String text)
    {
        if (text == null || "".equals(text.trim()) ||
                text.trim().length() == 0 || "null".equals(text.trim()))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 描述：手机号格式验证.
     *
     * @param str 指定的手机号码字符串
     * @return 是否为手机号码格式:是为true，否则false
     */
    public static Boolean isMobilePhone(String str)
    {
        Boolean isMobileNo = false;
        try
        {
            Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$");
            Matcher m = p.matcher(str);
            isMobileNo = m.matches();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return isMobileNo;
    }

    /**
     * 得到字符串长度
     *
     * @param text
     * @return
     */
    public static int getCharCount(String text)
    {
        String Reg    = "^[\u4e00-\u9fa5]{1}$";
        int    result = 0;
        for (int i = 0; i < text.length(); i++)
        {
            String b = Character.toString(text.charAt(i));
            if (b.matches(Reg)) result += 2;
            else result++;
        }
        return result;
    }

    public static String toUpper(String content)
    {
        String ret = "";
        for (int i = 0; i < content.length(); i++)
        {
            char ch = content.charAt(i);
            if(Character.isLetter(ch) && Character.isLowerCase(ch))
            {
                ch = Character.toUpperCase(ch);
                ret += ch;
            }
            else
            {
                ret += ch;
            }
        }
        return ret;
    }

    public static String toLower(String content)
    {
        String ret = "";
        for (int i = 0; i < content.length(); i++)
        {
            char ch = content.charAt(i);
            if(Character.isLetter(ch) && Character.isUpperCase(ch))
            {
                ch = Character.toLowerCase(ch);
                ret += ch;
            }
            else
            {
                ret += ch;
            }
        }
        return ret;
    }

    /**
     * 获取截取后的字符串
     *
     * @param text   原字符串
     * @param length 截取长度
     * @param isOmit 是否加上省略号
     * @return
     */
    public static String getSubString(String text, int length, boolean isOmit)
    {
        if (isNullOrEmpty(text))
        {
            return "";
        }
        if (getCharCount(text) <= length + 1)
        {
            return text;
        }

        StringBuffer sb     = new StringBuffer();
        String       Reg    = "^[\u4e00-\u9fa5]{1}$";
        int          result = 0;
        for (int i = 0; i < text.length(); i++)
        {
            String b = Character.toString(text.charAt(i));
            if (b.matches(Reg))
            {
                result += 2;
            }
            else
            {
                result++;
            }

            if (result <= length + 1)
            {
                sb.append(b);
            }
            else
            {
                if (isOmit)
                {
                    sb.append("...");
                }
                break;
            }
        }
        return sb.toString();
    }

    /**
     * 电话号码验证
     *
     * @param phoneNumber 手机号码
     * @return
     */
    public static boolean validatePhoneNumber(String phoneNumber)
    {
        Pattern pattern = Pattern.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(18[0-9]))\\d{8}$");
        Matcher m       = pattern.matcher(phoneNumber);
        return m.matches();
    }

    /**
     * 邮箱验证
     *
     * @param mail 邮箱
     * @return
     */
    public static boolean validateEmail(String mail)
    {
        Pattern pattern = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
        Matcher m       = pattern.matcher(mail);
        return m.matches();
    }

    /**
     * 身份证验证
     * @param pid
     * @return
     */
    public static String isPersonNumber(String pid)
    {
        return PersonCard.IDCardValidate(pid.toLowerCase());

//        int[] wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
//        //求余后的校验码
//        String xiaoy = "10X98765432";
//        if (pid.trim().length() != 18)
//        {
//            return false;
//        }
//
//        //获得身份证的前17位和第18位校验位
//        String pid17 = pid.substring(0, 17);
//        String pid18 = pid.substring(17);
//
//        int sum = 0;
//
//        //对前17位数字本体码加权求和 公式为：S = Sum(Ai * Wi), i = 0, ... , 16
//        for (int i = 0; i < 17; i++)
//        {
//            //这里的pid17[i]作为char类型必须先转换成string,否则会用char类型的ascII码进行计算
//            sum = sum + Integer.valueOf(pid17.charAt(i)) * wi[i];
//        }
//
//        //求余和校验位进行匹配
//        int y = sum % 11;
//
//        //获得正确的校验码，有x的校验并涉及到大小写所以得用string
//        String rightxiaoy = String.valueOf(xiaoy.charAt(y));
//        return true;
//
////        //判断用户输入的校验位和正确的校验码是否一致
////        if (pid18.equalsIgnoreCase(rightxiaoy))
////        {
////            return true;
////        }
////        else
////        {
////            return false;
////        }
    }

    /**
     * 验证字符串内容是否合法
     *
     * @param content 字符串内容
     * @return
     */
    public static boolean validateLegalString(String content)
    {
        String  illegal = "`~!#%^&*=+\\|{};:'\",<>/?○●★☆☉♀♂※¤╬の〆";
        boolean legal   = true;
        L1:
        for (int i = 0; i < content.length(); i++)
        {
            for (int j = 0; j < illegal.length(); j++)
            {
                if (content.charAt(i) == illegal.charAt(j))
                {
                    legal = false;
                    break L1;
                }
            }
        }
        return legal;
    }

    /**
     * 对流转化成字符串
     *
     * @param is
     * @return
     */
    public static String getContentByString(InputStream is)
    {
        try
        {
            if (is == null) return null;
            byte[]        b   = new byte[1024];
            int           len = -1;
            StringBuilder sb  = new StringBuilder();
            while ((len = is.read(b)) != -1)
            {
                sb.append(new String(b, 0, len));
            }
            return sb.toString();
        }
        catch (Exception e)
        {

        }
        return null;
    }

    /**
     * 对流转化成字符串
     *
     * @param is
     * @return
     */
    public static String getStringByStream(InputStream is)
    {
        try
        {
            BufferedReader in     = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer   buffer = new StringBuffer();
            String         line   = "";
            while ((line = in.readLine()) != null)
            {
                buffer.append(line + "\n");
            }
            return buffer.toString().replaceAll("\n\n", "\n");
        }
        catch (Exception e)
        {
        }
        return null;
    }

    /**
     * 截取字符串，去掉sign后边的
     *
     * @param source 原始字符串
     * @param sign
     * @return
     */
    public static String splitByIndex(String source, String sign)
    {
        String temp = "";
        if (isNullOrEmpty(source))
        {
            return temp;
        }
        int length = source.indexOf(sign);
        if (length > -1)
        {
            temp = source.substring(0, length);
        }
        else
        {
            return source;
        }
        return temp;
    }

    /**
     * 截取字符串，返回sign分隔的字符串
     */
    public static String splitNumAndStr(String res, String sign)
    {
        StringBuffer buffer;
        String       reg = "\\d+";
        Pattern      p   = Pattern.compile(reg);
        Matcher      m   = p.matcher(res);
        if (m.find())
        {
            buffer = new StringBuffer();
            String s = m.group();
            buffer.append(s);
            buffer.append(sign);
            buffer.append(res.replace(s, ""));
            return buffer.toString();
        }
        return null;
    }

    /**
     * 保留小数点后一位
     *
     * @param d
     * @return
     * @throws Exception
     */
    public static String formatNumber(double d)
    {
        try
        {
            DecimalFormat df = new DecimalFormat("#,##0.0");
            return df.format(d);
        }
        catch (Exception e)
        {
        }
        return "";
    }

    /**
     * 把对象放进map里
     *
     * @param o 实体
     */
    public static Map<String, String> getMapForEntry(Object o)
    {
        Map<String, String> map = new HashMap<String, String>();
        try
        {
            Field[] fields = o.getClass().getFields();
            for (Field f : fields)
            {
                String key = f.getName();
                try
                {
                    String value = (String) f.get(o);
                    if (StringUtils.isNullOrEmpty(value) || value.indexOf("不限") > -1)
                    {
                        continue;
                    }
                    map.put(key, value);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e)
        {
        }
        return map;
    }

    /*
     * 截取sign后边的数字
     */
    public static String getStringNum(String str, String sign)
    {
        String reg = ":split:";
        return str.replace(sign, reg).replaceAll(reg + "\\d+", "").replaceAll(" ", "").trim();

    }

    public static String getRegText(String xml, String tag)
    {
        Pattern pattern = Pattern.compile("<" + tag + ">(.*?)</" + tag + ">", Pattern.UNICODE_CASE | Pattern.DOTALL);
        Matcher m       = pattern.matcher(xml);
        if (m.find())
        {
            xml = m.group(1);
            xml = xml.replace("<![CDATA[", "").replace("<![cdata[", "").replace("]]>", "");
            return xml;
        }
        else
        {
            return null;
        }
    }

    /**
     * 判断价格是否为0或空
     */
    public static boolean isPriceZero(String price)
    {
        if (isNullOrEmpty(price))
        {
            return true;
        }
        price = splitByIndex(price, ".");
        if ("0".equals(price))
        {
            return true;
        }
        return false;
    }

    /**
     * 取价格的整数，去掉单位
     *
     * @param price
     * @return
     */
    public static String getPrice(String price)
    {
        Pattern p = Pattern.compile("^\\d+");
        Matcher m = p.matcher(price);
        if (m.find())
        {
            return m.group();
        }
        return "";
    }

    /**
     * 判断是否全为数字
     *
     * @param content
     * @return
     */
    public static boolean isAllNumber(String content)
    {
        boolean isAllNumber = true;
        if (isNullOrEmpty(content))
        {
            return false;
        }
        for (int i = 0; i < content.length(); i++)
        {
            if (content.charAt(i) < '0' || content.charAt(i) > '9')
            {
                isAllNumber = false;
                break;
            }
        }
        return isAllNumber;
    }

    /**
     * @param source
     * @return
     */
    public static String getPhone(String source)
    {
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < source.length(); i++)
        {
            if (source.charAt(i) >= '0' && source.charAt(i) <= '9')
            {
                ret.append(source.charAt(i));
            }
        }
        return ret.toString();
    }

    public static boolean isHttpUrl(String url)
    {
        if (StringUtils.isNullOrEmpty(url))
        {
            return false;
        }
        url = url.trim();
        if (url.length() <= 10)
        {
            return false;
        }
        if (url.substring(0, 7).equals("http://") || url.substring(0, 7).equals("HTTP://"))
        {
            return true;
        }

        if (url.substring(0, 8).equals("https://") || url.substring(0, 8).equals("HTTPS://"))
        {
            return true;
        }
        return false;
    }

    /**
     * String source = "验证码:[103762]。尊敬的[18984119434]会员，欢迎您使用车友助理。【车友助理】";
     * String code = getSubString('[',']',s,0);
     * 结果为:103762
     * String phone = getSubString('[',']',s,1);
     * 结果为:18984119434
     *
     * @param start  开始字符
     * @param end    结束字符
     * @param source 源字符串
     * @param id     第几组 从0开始
     * @return
     */
    public static String getSubString(char start, char end, String source, int id)
    {
        String  ret    = "";
        String  sb     = (source);
        boolean recode = false;
        int     group  = 0;
        for (int i = 0; i < sb.length(); i++)
        {
            if (sb.charAt(i) == start)
            {
                if (id == group)
                {
                    recode = true;
                }
                continue;
            }
            if (sb.charAt(i) == end)
            {
                recode = false;
                if (id == group)
                {
                    break;
                }
                group++;
                continue;
            }
            if (recode)
            {
                ret += sb.charAt(i);
            }
        }
        return ret;
    }

    /**
     *
     * @param longTime
     * @param format   yyyy年MM月dd日 HH时mm分ss秒
     * @return
     */
    public static String getDateTimeToString(long longTime, String format)
    {
        SimpleDateFormat sdf  = new SimpleDateFormat(format, Locale.getDefault());
        Date             date = new Date(longTime);
        return sdf.format(date);
    }

    /**
     *
     * @param timeString
     * @param format yyyy年MM月dd日 HH时mm分ss秒
     * @return
     */
    public static long getDateTimeToLong(String timeString, String format)
    {
        try
        {
            SimpleDateFormat simpleFormat = new SimpleDateFormat(format, Locale.getDefault());
            Date             date;
            date = simpleFormat.parse(timeString);
            long tm = date.getTime();
            return date.getTime();
        }
        catch (ParseException e)
        {
            Logger.showDebugMsg(Logger.s_error, "Exception", e.getMessage());
            return 0;
        }

    }


    public static final int SIZETYPE_B  = 1;//获取文件大小单位为B的double值
    public static final int SIZETYPE_KB = 2;//获取文件大小单位为KB的double值
    public static final int SIZETYPE_MB = 3;//获取文件大小单位为MB的double值
    public static final int SIZETYPE_GB = 4;//获取文件大小单位为GB的double值

    public static String getFileSizeString(long size)
    {
        if (size > 1073741824)
        {
            return FormetFileSize(size, SIZETYPE_GB) + "GB";
        }
        else if (size > 1048576)
        {
            return FormetFileSize(size, SIZETYPE_MB) + "MB";
        }
        else
        {
            //return FormetFileSize(size, SIZETYPE_KB) + "KB";
            return "小于1M";
        }
    }

    /**
     * 转换文件大小,指定转换的类型
     *
     * @param fileS
     * @param sizeType
     * @return
     */
    private static double FormetFileSize(long fileS, int sizeType)
    {
        DecimalFormat df           = new DecimalFormat("#.00");
        double        fileSizeLong = 0;
        switch (sizeType)
        {
            case SIZETYPE_B:
                fileSizeLong = Double.valueOf(df.format((double) fileS));
                break;
            case SIZETYPE_KB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1024));
                break;
            case SIZETYPE_MB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
                break;
            case SIZETYPE_GB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1073741824));
                break;
            default:
                break;
        }
        return fileSizeLong;
    }

    public static byte[] getBytesFromFile(File file) throws IOException
    {
        InputStream is = new FileInputStream(file);
        byte[] bytes;

        try {
            // Get the size of the file
            long length = file.length();

            // You cannot create an array using a long type.
            // It needs to be an int type.
            // Before converting to an int type, check
            // to ensure that file is not larger than Integer.MAX_VALUE.
            if (length > Integer.MAX_VALUE) {
                // File is too large (>2GB)
            }

            // Create the byte array to hold the data
            bytes = new byte[(int)length];

            // Read in the bytes
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length
                    && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
                offset += numRead;
            }

            // Ensure all the bytes have been read in
            if (offset < bytes.length) {
                throw new IOException("Could not completely read file " + file.getName());
            }
        }
        finally {
            // Close the input stream and return bytes
            is.close();
        }
        return bytes;
    }
}
